package com.xinqi.common.green.utils;

import cn.hutool.dfa.WordTree;
import com.xinqi.common.base.constants.SensitiveWordConstant;
import com.xinqi.common.core.utils.SpringUtils;
import com.xinqi.common.redis.utils.Caches;
import org.apache.commons.collections4.CollectionUtils;
import org.apache.commons.lang3.StringUtils;
import org.redisson.api.RedissonClient;

import java.util.List;
import java.util.Set;
import java.util.stream.Collectors;

/**
 * @version V1.0
 * @Title: 敏感词校验工具类
 * @ClassName: com.xinqi.common.green.utils.SensitiveWordUtils.java
 * @Description:
 * @Copyright 星齐科技（云南）有限公司 - Powered By 技术部
 * @author: yyzhen
 * @date: 2023/8/3 17:29
 */
public class SensitiveWordUtils {

    private static final RedissonClient redissonClient = SpringUtils.getBean(RedissonClient.class);

    /**
     * 检查敏感信息，
     *
     * @param text 待检验的文本
     * @return boolean 不包含敏感信息返回true，包含敏感信息返回false
     */
    public static boolean checkSensitiveWord(String text) {
        if (StringUtils.isEmpty(text)) {
            return Boolean.TRUE;
        }
        WordTree tree = getAllEffectiveSensitiveWord();
        if (tree.isEmpty()) {
            return Boolean.TRUE;
        }
        return !tree.isMatch(text);
    }

    /**
     * 检查敏感信息，
     * 存在敏感词，敏感词用*代替
     * @param text 待检验的文本
     * @return boolean 不包含敏感信息返回true，包含敏感信息返回false
     */
    public static String checkReplaceSensitiveWord(String text) {
        if (StringUtils.isEmpty(text)) {
            return null;
        }
        WordTree tree = getAllEffectiveSensitiveWord();
        if (tree.isEmpty()) {
            return null;
        }
        List<String> sensitiveList = tree.matchAll(text).stream().distinct().collect(Collectors.toList());
        if (CollectionUtils.isNotEmpty(sensitiveList)) {
            for (String sensitive : sensitiveList) {
                text = text.replaceAll(sensitive, "***");
            }
            return text;
        } else {
            return null;
        }
    }

    public static WordTree getAllEffectiveSensitiveWord() {
        WordTree tree = new WordTree();

        Set<String> wordSet = Caches.get(redissonClient, SensitiveWordConstant.SENSITIVE_WORD_KEY);
        if (CollectionUtils.isNotEmpty(wordSet)) {
            for (String word : wordSet) {
                tree.addWord(word);
            }
        }

        return tree;
    }
}
